<template>
    <div class='inExecution'>
        <div class='step'>第一步：选择参与匹配绩效工资的业务对象的属性（最多20个）</div>
        <div class='addDimension'>
            <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" :disabled="dimesionDis"
                @click="addDimension">新增绩效工资取数维度</el-button>
        </div>
        <div class="table">
            <el-table :data="wd_tableList" border style="width: 600px;"
                :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}" 
                ref='selTable1'>
                <el-table-column
                    v-for="(item, i) in wd_tableHeaderList"
                    :label="item.name"
                    :prop="item.label"
                    :width="item.width"
                    :sortable="item.sortable"
                    :fixed="item.fixed"
                    show-overflow-tooltip
                    :key='i'
                >
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="80">
                    <template slot-scope="scope">
                        <el-popconfirm title="这是一段内容确定删除吗？" @confirm='wd_del(scope.row)'>
                            <el-button type="text" size="small" slot="reference">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
                <div slot="empty">
                    <el-empty :image-size="100"></el-empty>
                </div>
            </el-table>
        </div>
        <div class='step'>第二步：设定多业务对象属性组合的优先级（最多20级）</div>
        <div class='addCombination'>
            <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" :disabled="combinationDis"
                @click="addCombination">新增绩效工资维度组合</el-button>
        </div>
        <div class="table">
            <el-table :data="zh_tableList" border style="width: 800px;"
                :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}"
                ref='selTable'>
                <el-table-column
                    v-for="(item, i) in zh_tableHeaderList"
                    :label="item.name"
                    :prop="item.label"
                    :width="item.width"
                    :sortable="item.sortable"
                    :fixed="item.fixed"
                    show-overflow-tooltip
                    :key='i'
                >
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="rowMove(scope.row, 'up')">上移</el-button>
                        <el-button type="text" size="small" @click="rowMove(scope.row, 'down')">下移</el-button>
                        <el-button type="text" size="small" @click="zh_edit(scope.row)">编辑</el-button>
                        <el-popconfirm title="这是一段内容确定删除吗？" @confirm='zh_del(scope.row)' class='del'>
                            <el-button type="text" size="small" slot="reference">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
                <div slot="empty">
                    <el-empty :image-size="100"></el-empty>
                </div>
            </el-table>
        </div>
        <div class='step'>
            第三步：草稿方案生效前，如果第一步的业务对象属性有增/删/移动操作，生效将清除现有的工价数据。建议备份后再点击生效（路径：绩效工资配置 > 导出数据）如果第一步的业务对象属性没有变化，现有的工价数据仍然可以使用，只是匹配的优先级有所调整
        </div>
        <div class='btn'>
            <el-button type="primary" size="small" @click="handleSave">保存</el-button>
            <el-button type="primary" size="small" @click="takeEffect">生效</el-button>
            <el-button plain size="mini" @click="handleCancel">取消</el-button>
        </div>

        <!-- 新增绩效工资取数维度 -->
        <el-dialog title="添加绩效工资取数维度" :visible.sync="wd_dialog" width='400px' @close="wd_handleClose">
            <el-form :model="createForm" :rules="rules" ref="createForm" label-width="" size="mini">
                <el-form-item label="业务对象/属性" prop="businessObject">
                    <el-cascader
                        v-model="createForm.businessObject"
                        :options="options"
                        @change="cascaderChange"
                        :props='cateProps'
                    >
                    </el-cascader>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleCancle('wd')">取 消</el-button>
                <el-button type="primary" @click="handleOk('wd')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增绩效工资维度组合 -->
        <el-dialog title="新增绩效工资维度组合" :visible.sync="zh_dialog" width='520px' :before-close="zh_handleClose">
            <el-table :data="wd_tableList" border style="width: 100%;"
                :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}"
                @selection-change="handleSelectionChange" ref='selTable'>
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column
                    v-for="(item, i) in dialogTable"
                    :label="item.name"
                    :prop="item.label"
                    :width="item.width"
                    :sortable="item.sortable"
                    :fixed="item.fixed"
                    show-overflow-tooltip
                    :key='i'
                >
                </el-table-column>
                <div slot="empty">
                    <el-empty :image-size="100"></el-empty>
                </div>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleCancle('zh')">取 消</el-button>
                <el-button type="primary" @click="handleOk('zh')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 确认生效 -->
        <el-dialog
            :visible.sync="effectDialog"
            width="30%">
            <p slot='title' class="effect">
                <span class="el-icon-warning-outline"></span>
                确定生效
            </p>
            <span>草稿规则将复制到执行中，请确认？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="effectDialog = false">取 消</el-button>
                <el-button type="primary" @click="effectSure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    insertWagesList,
    npmRuleHandle,
    npmRuleTakeEffect,
    mpmRuleList
} from '@/api/baseController'
export default {
    data() {
        return {
            //绩效工资取数维度表格
            wd_tableHeaderList: [
                {
                    label: 'index',
                    name: '序号',
                    width: '55',
                },
                {
                    label: 'businessObject',
                    name: '业务对象',
                    width: ''
                },
                {
                    label: 'attribute',
                    name: '属性',
                    width: ''
                }
            ],
            wd_tableList: [],
            // 绩效公司维度组合表格
            zh_tableHeaderList: [
                {
                    label: 'level',
                    name: '优先级',
                    width: '65',
                },
                {
                    label: 'combination',
                    name: '绩效维度组合',
                    width: ''
                }
            ],
            zh_tableList: [],
            // 新增维度对话框
            wd_dialog: false,
            createForm: {
                businessObject: []
            },
            options: [],
            cateProps: {
                label: 'name',
                value: 'name',
                children: 'listDown'
            },
            rules: {
                businessObject: [
                    {
                        required: true,
                        message: '业务对象/属性 不能为空!'
                    }
                ]
            },
            // 组合对话框
            zh_dialog: false,
            dialogTable: [
                {
                    label: 'index',
                    name: '序号',
                    width: '65',
                },
                {
                    label: 'businessObject',
                    name: '业务对象',
                    width: ''
                },
                {
                    label: 'attribute',
                    name: '属性',
                    width: ''
                }
            ],
            dialogTableSel: [],
            dimesionDis: false,
            combinationDis: false,
            effectDialog: false,
            zh_id: '',
            wdChange: [], // 维度数组不变更则为0-生效后不清除列表， 变更则为1-生效后清除列表
        }
    },
    mounted() {
        this.getInsertWagesList()
        this.getMpmRuleList()
    },
    methods: {
        // 接口============================
        getInsertWagesList() {
            insertWagesList().then(res => {
                if(res.code == 200) {
                    this.options = res.data
                }
            })
        },
        // 保存草稿
        getNpmRuleHandle(n) {
            let data = this.apiData()
            data.state = 0
            npmRuleHandle(data).then(res => {
                if(res.code == 200) {
                    if(n == 'sx') {
                        this.getNpmRuleTakeEffect()
                    } else {
                        this.utils.showMsg('保存草稿成功', 'success')
                    }
                }
            })
        },
        // 生效
        getNpmRuleTakeEffect() {
            let data = this.apiData()
            JSON.stringify(this.wd_tableList) === JSON.stringify(this.wdChange) ? data.type = 0 : data.type = 1
            data.state = 1
            npmRuleHandle(data).then(res => {
                if(res.code == 200) {
                    this.utils.showMsg('草稿生效成功', 'success')
                }
            })
        },
        // 表格初始
        getMpmRuleList() {
            mpmRuleList({}).then(res => {
                if(res.code == 200) {
                    if(res.data) {
                        res.data.dimensionCombinations.map(item => {
                            this.zh_tableList.push({
                                combination: item.combination,
                                level: item.level
                            })
                        })
                        res.data.matchingRules.map(item => {
                            this.wd_tableList.push({
                                index: this.wd_tableList.length + 1,
                                businessObject: item.businessObject,
                                attribute: item.attribute,
                                cusField: item.cusField
                            })
                            this.wdChange.push({
                                index: this.wdChange.length + 1,
                                businessObject: item.businessObject,
                                attribute: item.attribute,
                                cusField: item.cusField
                            })
                        })
                    }
                }
            })
        },

        // 事件================================
        // 新增绩效工资取数维度
        addDimension() {
            this.wd_dialog = true;
            this.options.map(item => {
                if(item.listDown != null && item.listDown.length > 0) {
                    item.listDown.map(k => {
                        let d = this.wd_tableList.find(res => { return res.attribute == k.name })
                        let cusField = this.wd_tableList.find(res => { return res.cusField == k.cusField })
                        if(d != undefined || cusField != undefined) {
                            k.disabled = true
                        } else {
                            k.disabled = false
                        }
                    })
                } else {
                    let d = this.wd_tableList.find(res => { return res.businessObject == item.name })
                    if(d != undefined) {
                        item.disabled = true
                    } else {
                        item.disabled = false
                    }
                }
            })
        },
        // 新增绩效工资维度组合
        addCombination() {
            this.zh_id = ''
            this.zh_dialog = true;
        },
        // 维度表格删除操作
        wd_del(v) {
            var arr = []
            this.wd_tableList.splice((v.index - 1), 1)
            this.wd_tableList.map((item, i) => {
                item.index = i + 1
            })
            this.zh_tableList.map(item => {
                if(item.combination.indexOf(v.businessObject) == -1) {
                    arr.push(item)
                }
            })
            this.zh_tableList = arr;
            this.utils.showMsg('删除成功', 'success')
            if(this.wd_tableList.length < 20) {
                this.dimesionDis = false
            }
        },
        // 维度弹框下拉选择
        cascaderChange() {

        },
        // 组合表格编辑操作
        zh_edit(d) {
            this.zh_dialog = true;
            this.zh_id = d.level
            this.$nextTick(() => {
                this.wd_tableList.map((item, i) => {
                    if(d.combination.indexOf(item.businessObject+'.'+item.attribute) != -1) {
                        this.$refs.selTable.toggleRowSelection(this.wd_tableList[i], true);
                    }
                })
            })
        },
        // 组合表格删除操作
        zh_del(v) {
            this.zh_tableList.splice((v.level - 1), 1)
            this.zh_tableList.map((item, i) => {
                item.level = i + 1
            })
            this.utils.showMsg('删除成功', 'success')
            if(this.zh_tableList.length < 20) {
                this.combinationDis = false
            }
        },
        // 上移下移
        rowMove(row, t) {
            if(t == 'up') {
                if(row.level != 1) {
                    let d = this.zh_tableList.findIndex(res => { return res.level == row.level })
                    let data = this.zh_tableList[d]
                    this.$set(this.zh_tableList, d, this.zh_tableList[d-1])
                    this.$set(this.zh_tableList, d-1, data)
                    // this.zh_tableList[d] = this.zh_tableList[d-1]
                    // this.zh_tableList[d-1] = data
                }
            } else {
               if(row.level != this.zh_tableList.length) {
                    let d = this.zh_tableList.findIndex(res => { return res.level == row.level })
                    let data = this.zh_tableList[d]
                    this.$set(this.zh_tableList, d, this.zh_tableList[d+1])
                    this.$set(this.zh_tableList, d+1, data)
                    // this.zh_tableList[d] = this.zh_tableList[d+1]
                    // this.zh_tableList[d+1] = data
                }
            }
            this.zh_tableList.map((item, i) => {
                item.level = i + 1
            })
        },
        // 保存
        handleSave() {
            this.saveRule('save')
        },
        // 生效
        takeEffect() {
            this.saveRule('effect')
        },
        // 确认生效
        effectSure() {
            this.effectDialog = false
            this.getNpmRuleHandle('sx')
        },
        saveRule(t) {
            if(this.wd_tableList.length == 0) {
                this.utils.showMsg('至少选择一个业务属性对象', 'warning')
                return
            } if(this.zh_tableList.length == 0) {
                this.utils.showMsg('至少选择一个绩效工资维度组合', 'warning')
                return
            } else {
                if(t == 'save') {
                    this.getNpmRuleHandle()
                } else {
                    this.effectDialog = true
                }
            }
        },
        // 接口参数
        apiData() {
            let matchingRules = []
            let dimensionCombinations = []
            this.wd_tableList.map(item => {
                item.node = this.options.find(res => { return res.name == item.businessObject })
            })
            this.wdChange.map(item => {
                item.node = this.options.find(res => { return res.name == item.businessObject })
            })

            this.wd_tableList.map(item => {
                matchingRules.push({
                    businessObject: item.businessObject,
                    attribute: item.attribute,
                    cusField: !item.cusField ? (item.node.listDown.find(k => { return k.name == item.attribute })).cusField : item.cusField
                })
            })
            this.zh_tableList.map(item => {
                dimensionCombinations.push({
                    combination: item.combination,
                    level: item.level
                })
            })

            let data = {
                matchingRules: matchingRules,
                dimensionCombinations: dimensionCombinations
            }
            return data
        },
        // 取消
        handleCancel() {
            this.$router.push('/basicData/meritPay')
        },
        // 弹框取消事件
        handleCancle(v) {
            if(v == 'wd') {
                this.createForm.businessObject = [];
                this.wd_dialog = false;
            } else {
                this.zh_dialog = false;
                this.dialogTableSel = []
                this.$refs.selTable.clearSelection();
            }
        },
        handleOk(v) {
            if(v == 'wd') {
                this.$refs.createForm.validate((valid) => {
                    if (valid) {
                        if(this.createForm.businessObject.length == 1) {
                            this.options.map(item => {
                                if(item.name == this.createForm.businessObject[0]) {
                                    item.disabled = true
                                }
                            })
                        } else {
                            this.options.map(item => {
                                if(item.listDown) {
                                    item.listDown.map(k => {
                                        if(k.name == this.createForm.businessObject[1]) {
                                            k.disabled = true
                                        }
                                    })
                                }
                            })
                        }
                        this.wd_tableList.push({
                            index: this.wd_tableList.length + 1,
                            businessObject: this.createForm.businessObject[0],
                            attribute: this.createForm.businessObject[1] ? this.createForm.businessObject[1] : '',
                        })
                        this.wd_dialog = false
                        
                        if(this.wd_tableList.length >= 20) {
                            this.dimesionDis = true
                        }
                        this.createForm.businessObject = [];
                    } else {
                        return false;
                    }
                });
            } else {
                var str = ''
                var state = true
                this.dialogTableSel.map(item => {
                    str = str + item.businessObject + '.' + item.attribute + ','
                })
                str = str.substr(0, str.length - 1)
                this.zh_tableList.map(item => {
                    if(item.combination == str) {
                        this.utils.showMsg('当前组合已存在,请重新选择', 'warning')
                        state = false
                    }
                })
                if(this.dialogTableSel.length < 1) {
                    this.utils.showMsg('至少选择一个业务对象', 'warning')
                    state = false
                }
                if(state) {
                    this.zh_dialog = false
                    if(this.zh_id != '') {
                        let obj = {
                            level: this.zh_id,
                            combination: str,
                        }
                        this.$set(this.zh_tableList, this.zh_id - 1, obj)
                    } else {
                        this.zh_tableList.push({
                            level: this.zh_tableList.length + 1,
                            combination: str,
                        })
                    }
                    this.dialogTableSel = []
                    this.$refs.selTable.clearSelection();
                }
                
                if(this.zh_tableList.length >= 20) {
                    this.combinationDis = true
                }
            }
        },
        wd_handleClose() {
            // this.createForm.businessObject = [];
            this.$set(this.createForm, 'businessObject', [])
            this.wd_dialog = false;
        },
        zh_handleClose() {
            this.zh_dialog = false;
            this.dialogTableSel = []
            this.$refs.selTable.clearSelection();
        },
        // 表格勾选
        handleSelectionChange(val) {
            this.dialogTableSel = val
        }
    }
}
</script>

<style lang="less" scoped>
.inExecution {
    .step {
        font-size: 12px;
        margin-bottom: 10px;
    }
    .addDimension, .addCombination {
        margin-bottom: 10px;
    }
    .table {
        margin-bottom: 20px;
        .del {
            margin-left: 10px;
        }
    }
    .btn {
        display: flex;
        justify-content: center;
        button {
            width: 100px;
        }
    }
    .effect {
        display: flex;
        align-items: center;
        color: #606266;
        span {
            font-size: 22px;
            margin-right: 5px;
            color: #faad14;
        }
    }
    /deep/ .el-dialog__body {
        // padding: 30px 40px;
    }
}
</style>